package indi.zhang.rabbitlistener.listener;

import com.rabbitmq.client.Channel;
import indi.zhang.rabbitlistener.config.RabbitConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class OperationLogBatchConsumer implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {

    }

    @RabbitListener(queues = RabbitConfig.OPERATION_LOG_QUEUE, containerFactory = "consumerBatchContainerFactory")
    @Override
    public void onMessageBatch(List<Message> messages, Channel channel) {
        try {
            log.info("batch.queue.consumer 收到{}条message", messages.size());
            if (messages.size() > 0) {
                log.info("第一条数据是: {}", new String(messages.get(0).getBody()));
            }

            channel.basicAck(messages.size(), true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            for (Message message : messages) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
                // channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
